package command

import (
	"context"
	rawNet "net"

	"google.golang.org/grpc"
	"google.golang.org/grpc/grpclog"

	"github.com/gogf/gf/v2/frame/g"

	grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
	grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
	grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
	grpcopentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing"

	"github.com/beherochuling/beesoft_api/app/helper/net"
	"github.com/beherochuling/beesoft_api/router"
)

func init() {
	// bootGrpc()
}

func bootGrpc() {
	ctx := context.Background()

	rootCaFile := g.Config().MustGet(ctx, "tls.rootCaFile").String()
	certFile := g.Config().MustGet(ctx, "tls.backend.certFile").String()
	keyFile := g.Config().MustGet(ctx, "tls.backend.certFile").String()
	opt := grpc.Creds(net.NewTls(rootCaFile, certFile, keyFile).Server())
	opt1 := grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(
		grpc_ctxtags.StreamServerInterceptor(),
		grpcopentracing.StreamServerInterceptor(),
		// grpc_prometheus.StreamServerInterceptor,
		// grpc_zap.StreamServerInterceptor(zapLogger),
		// grpc_auth.StreamServerInterceptor(myAuthFunction),
		grpc_recovery.StreamServerInterceptor(),
	))
	opt2 := grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
		grpc_ctxtags.UnaryServerInterceptor(),
		grpcopentracing.UnaryServerInterceptor(),
		// grpc_prometheus.UnaryServerInterceptor,
		// grpc_zap.UnaryServerInterceptor(zapLogger),
		// grpc_auth.UnaryServerInterceptor(myAuthFunction),
		grpc_recovery.UnaryServerInterceptor(),
	))
	// s := grpc.NewServer()
	s := grpc.NewServer(opt, opt1, opt2)

	router.Register(s)

	protocol := g.Config().MustGet(ctx, "grpc.protocol").String()
	port := g.Config().MustGet(ctx, "grpc.port").String()
	listen, err := rawNet.Listen(protocol, port)
	if err != nil {
		grpclog.Fatalf("Failed to listen: %v", err)
	}

	err = s.Serve(listen)
	if err != nil {
		grpclog.Fatalf("Failed to serve: %v", err)
	}
}
